﻿using System;
using System.Data;
using System.Data.SqlServerCe;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using SerbinAV.MobileSales.Sales.Entities;


namespace SerbinAV.MobileSales.Sales.DAL
{
    public class SkladRepository:ISkladRepository
    {

        private string _connectionString;

        public SkladRepository(string connectionString)
        {
            _connectionString = connectionString;
        }

        public List<Sklad> GetAll()
        {
            List<Sklad> sklads = new List<Sklad>();
            using (SqlCeConnection connection = new SqlCeConnection(_connectionString))
            {
                if (connection.State != ConnectionState.Open)
                    connection.Open();

                string sqlQuery = "SELECT IdSklad, NameSklad FROM Sklads";

                using (SqlCeCommand command = new SqlCeCommand(sqlQuery, connection))
                {
                    using (SqlCeDataReader dr = command.ExecuteReader())
                    {
                        while (dr.Read())
                        {
                            sklads.Add(EntityReader.ReadSklad(dr));
                        }
                        return sklads;
                    }
                }
            }
        }

        public Sklad GetSkladById (int id)
        {
            using (SqlCeConnection connection = new SqlCeConnection(_connectionString))
            {
                if (connection.State != ConnectionState.Open)
                    connection.Open();

                string sqlQuery =
                    "SELECT IdSklad, NameSklad" +
                    "FROM Sklads " +
                    "Where IdSklad = @IdSklad";

                using (SqlCeCommand command = new SqlCeCommand(sqlQuery, connection))
                {
                    command.Parameters.Add("@IdSklad", id);
                    using (SqlCeDataReader dr = command.ExecuteReader())
                    {
                        Sklad sklad = new Sklad();
                        if (dr.Read())
                        {
                            sklad = EntityReader.ReadSklad(dr);
                        }
                        return sklad;
                    }
                }
            }
        }
    }
}
